﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
public class UIMgr : Sington<UIMgr> {
    Transform root;
   public Dictionary<E_UILayer, Transform> LayerDic = new Dictionary<E_UILayer, Transform>();
    public List<UIBase> UIList = new List<UIBase>();
    Dictionary<Type, UIBase> UIDic = new Dictionary<Type, UIBase>();
    public Dictionary<UIBase, List<UIBase>> MultiUIDic = new Dictionary<UIBase, List<UIBase>>();
    public void Init() {
        root = GameObject.Find("UIRoot").transform;
        foreach (var item in Enum.GetValues(typeof( E_UILayer)))
        {
            LayerDic.Add((E_UILayer)item , root.Find(item.ToString()));
        }
    }

    public void CreateGO(UIBase ui) 
    {
        ui.gameObject = ResMgr.Instance.LoadUI(ui.Path);
        ui.transform = ui.gameObject.transform;
        ui.RectTrans = ui.transform as RectTransform;
        ui.transform.SetParent(LayerDic[ui.Layer],false);
        if(!ui.CanMulti)
        UIDic.Add(ui.GetType(),ui);
        UIList.Add(ui);
    }
    public T CreateUI<T>(object info=null) where T:UIBase
    {
        UIBase ui = GetUI(typeof(T));
        if (ui != null)
        {
            if (ui.CanMulti)
            {
                if (ui.gameObject.activeInHierarchy)
                {
                    UIBase uinew = Activator.CreateInstance(typeof(T)) as UIBase;
                    if (!MultiUIDic.ContainsKey(ui))
                    {
                        List<UIBase> MultiList = new List<UIBase>();
                        MultiList.Add(uinew);
                        MultiUIDic.Add(ui, MultiList);
                    }
                    else
                    {
                        List<UIBase> MultiList = MultiUIDic[ui];
                        MultiList.Add(uinew);
                    }
                    uinew.Open(info);
                    return uinew as T;
                }
                else
                {
                    ui.gameObject.SetActive(true);
                    return ui as T;
                }
               
            }
            else
            {
                ui.gameObject.SetActive(true);
                ui.UpdateInfo();
                return ui as T;
            }
        }
        else
        {
            ui = Activator.CreateInstance(typeof(T)) as UIBase;
            ui.Open(info);
            return ui as T;
        }

    }

    UIBase GetUI(Type t)
    {
        if (UIDic.ContainsKey(t))
            return UIDic[t];
        return null;
    }
}
